package com.htbb.common.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

import com.htbb.common.util.DateUtil;



/**
 * 类名称：MqSender    
 * 类描述：消息队列发送端
 * 创建人：wuyongde  
 * 创建时间：2017-4-12 下午03:54:41    
 * 修改人：wuyongde   
 * 修改时间：2017-4-12 下午03:54:41    
 * 修改备注：    
 * @version 1.0  
 */
public class MqSender {

	private final static Logger logger = Logger.getLogger(MqSender.class);

	private static ConnectionFactory connectionFactory = null;  //ConnectionFactory ：连接工厂，JMS 用它创建连接 
	private static Connection connection = null;  // Provider 的连接  
	private static Session session = null; //Session： 一个发送或接收消息的线程  

	protected static MqSender mqSender = new MqSender();

	private static Long isuId = System.currentTimeMillis();
	
//	public String MQ_SERVER = "tcp://172.16.100.193:61616";
	public String MQ_SERVER = "tcp://120.24.70.109:61616";
//	public String MQ_SERVER = "failover:(tcp://TST-MQ-01:61616,tcp://172.16.100.193:61616)?randomize=false";
	
	public MqSender(){
		init();
	}

	/**
	 * 获取唯一实例.
	 * @return
	 */
	public static MqSender getInstance(){
		if (mqSender == null) {
			mqSender = new MqSender();
		}
		return mqSender;
	}

	/**
	 * 获取session
	 * @return
	 */
	public Session getSession(){
		return session;
	}

	/**
	 * 初始化链接
	 */
	public void init(){

		// 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar  
		if(connectionFactory == null){
			connectionFactory = new ActiveMQConnectionFactory(
					ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD,Config.MQ_SERVER==null?MQ_SERVER:Config.MQ_SERVER);
		}

		try{
			if(connection == null){
				// 构造从工厂得到连接对象  
				connection = connectionFactory.createConnection();
				//启动
				connection.start();
			}

			if(session == null){
				// 获取操作连接  
				session = connection.createSession(Boolean.FALSE.booleanValue(), 
						Session.AUTO_ACKNOWLEDGE);
			}

		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		try {
			System.out.println("Producer:->Closing connection");

			if (session != null)
				session.close();
			if (connection != null)
				connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 消息发送
	 * · StreamMessage -- Java原始值的数据流

		· MapMessage--一套名称-值对

		· TextMessage--一个字符串对象

		· ObjectMessage--一个序列化的 Java对象

		· BytesMessage--一个未解释字节的数据流
	 */
	public static void sendTextMessage(String msg,String mqname){

		try {

			//获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置  
			Destination destination = session.createQueue(mqname);
			// 得到消息生成者【发送者】 
			MessageProducer producer = session.createProducer(destination);
			// 设置不持久化，此处学习，实际根据项目决定  
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

			//发送消息
			TextMessage message = session.createTextMessage(msg); 
			producer.send(message); 
			//session创建如果采用非事务方式无须手动提交
//			session.commit();

			//关闭producer
			producer.close();

		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送map方式
	 * @param message
	 * @param mqname
	 */
	public static void sendMapMessage(MapMessage message,String mqname){

		try {

			//获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置  
			Destination destination = session.createQueue(mqname);
			// 得到消息生成者【发送者】 
			MessageProducer producer = session.createProducer(destination);
			// 设置不持久化，此处学习，实际根据项目决定  
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

			//发送消息
			producer.send(message); 
			//session创建如果采用非事务方式无须手动提交
//			session.commit();

			//关闭producer
			producer.close();

		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			System.out.println("开始时间："+DateUtil.getSQLDate());
			String mqname = "ORDER";
			
			MapMessage message = MqSender.getInstance().getSession().createMapMessage();
			
			message.setInt("type", 4);
			for(int i=0;i<1;i++){
//				isuId = isuId +1;
				isuId = 11141100008l;
			
//				String jsonmsg = "{isuId:"+isuId+",isuNumTuan:\"T122112\",userId:\"1000000008\",prodId:\"1001\",prodName:\"员工重大疾病险\","
//						+ "skuId:\"100101\",isuAmt:\"200000\",custName:\"小五\",custPhone:\"15814403512\","
//						+ "custIdType:\"1\",custIdNum:\"432524199009220634\",isuName:\"小五\""
//						+ ",isuPhone:\"15814403512\",isuIdType:\"1\",isuIdNum:\"432524199009220000\","
//						+ "isuBirthday:\"1990-09-22\",isuSex:\"1\",relation:\"1\",benefit:\"法定受益人\""
//						+ ",email:\"wuyongde@htbaobao.com\",deptId:\"14011373\",isuFee:\"11000\",userNum:\"122\","
//						+ "userName:\"DS\",isuType:\"1\",deptName:\"顺丰/速运事业群/系统需求分析处/需求运营组\",skuName:\"家属方案2（父母）\",isuWay:\"1\"}";
				
//				String jsonmsg = "{isuId:"+isuId+",userId:\"1000000008\",isuStatus:\"7\",isuPhone:\"15814403512\"}";
//				String jsonmsg = "{payId:1321321,isuId:\"1493091562923\",prodName:\"员工重大疾病险\",payAmt:\"11000\",appType:\"2\",notifyUrl:\"https://www.baidu.com/\"}";
				String jsonmsg = "{isuId:\"1493030795605,1493030841612\"}";
				
				message.setString("jsonMsg", jsonmsg);
				
				MqSender.getInstance().sendMapMessage(message, mqname);
			}
			System.out.println("结束时间："+DateUtil.getSQLDate());
		} catch (Exception e) {
			System.out.println("发送失败----");
			e.printStackTrace();
		}
	}
	
}
